package com.xuecheng.learning.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.model.po.CoursePublish;
import com.xuecheng.learning.feignclient.ContentServiceClient;
import com.xuecheng.learning.mapper.XcChooseCourseMapper;
import com.xuecheng.learning.mapper.XcCourseTablesMapper;
import com.xuecheng.learning.model.dto.MyCourseTableParams;
import com.xuecheng.learning.model.dto.XcChooseCourseDto;
import com.xuecheng.learning.model.dto.XcCourseTablesDto;
import com.xuecheng.learning.model.po.XcChooseCourse;
import com.xuecheng.learning.model.po.XcCourseTables;
import com.xuecheng.learning.service.MyCourseTablesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class MyCourseTablesServiceImpl implements MyCourseTablesService {


    @Autowired
    XcChooseCourseMapper xcChooseCourseMapper;

    @Autowired
    XcCourseTablesMapper xcCourseTablesMapper;

    @Autowired
    ContentServiceClient client;

    @Autowired
    MyCourseTablesServiceImpl currentProxy;

    /**
     * 进行选课
     *
     * @param userId
     * @param courseId
     * @return
     */
    @Override
    @Transactional
    public XcChooseCourseDto addChooseCourse(String userId, Long courseId) {

        //查询课程信息
        CoursePublish coursepublish = client.getCoursepublish(courseId);
        //获取收费规则
        String charge = coursepublish.getCharge();
        //选课记录
        XcChooseCourse chooseCourse = null;
        //判断课程付费还是收费
        if ("201000".equals(charge)) { //课程免费
            //添加到选课记录表中--免费模式
            chooseCourse = addFreeCourse(userId, coursepublish);

            //添加到我的课程表中
            XcCourseTables xcCourseTables = addCourseTabls(chooseCourse);
        } else {
            //添加到选课记录表中--付费模式
            chooseCourse = addChargeCoruse(userId, coursepublish);
        }

        //获取学习资格
        XcCourseTablesDto courseTablesDto = getLearningStatus(userId, courseId);

        //创建返回对象--将学习资格状态赋值
        XcChooseCourseDto xcChooseCourseDto = new XcChooseCourseDto();
        xcChooseCourseDto.setLearnStatus(courseTablesDto.getLearnStatus());

        //复制
        BeanUtils.copyProperties(chooseCourse, xcChooseCourseDto);


        return xcChooseCourseDto;


    }


    /**
     * 将课程记录表中的课程添加到我的课程中
     *
     * @param chooseCourse
     * @return
     */
    public XcCourseTables addCourseTabls(XcChooseCourse chooseCourse) {
        //进行校验
        String status = chooseCourse.getStatus();
        if (!"701001".equals(status)) {
            XueChengPlusException.cast("选课未成功，无法添加到课程表");
        }
        //查询我的课程表
        XcCourseTables xcCourseTables = getXcCourseTables(chooseCourse.getUserId(), chooseCourse.getCourseId());
        if (xcCourseTables != null) {
            return xcCourseTables;
        }

        //未查询到需要将课程信息添加到我的课程表中
        XcCourseTables xcCourseTablesNew = new XcCourseTables();
        xcCourseTablesNew.setChooseCourseId(chooseCourse.getId());
        xcCourseTablesNew.setUserId(chooseCourse.getUserId());
        xcCourseTablesNew.setCourseId(chooseCourse.getCourseId());
        xcCourseTablesNew.setCompanyId(chooseCourse.getCompanyId());
        xcCourseTablesNew.setCourseName(chooseCourse.getCourseName());
        xcCourseTablesNew.setCreateDate(LocalDateTime.now());
        xcCourseTablesNew.setValidtimeStart(chooseCourse.getValidtimeStart());
        xcCourseTablesNew.setValidtimeEnd(chooseCourse.getValidtimeEnd());
        xcCourseTablesNew.setCourseType(chooseCourse.getOrderType());
        xcCourseTablesMapper.insert(xcCourseTablesNew);

        return xcCourseTablesNew;

    }

    /**
     * 查询课程表
     *
     * @param userId
     * @param courseId
     * @return
     */
    public XcCourseTables getXcCourseTables(String userId, Long courseId) {
        XcCourseTables xcCourseTables = xcCourseTablesMapper.selectOne(new LambdaQueryWrapper<XcCourseTables>().eq(XcCourseTables::getCourseId, courseId).eq(XcCourseTables::getUserId, userId));
        if (xcCourseTables == null) {
            XueChengPlusException.cast("未查询到我的课程信息");
        }
        return xcCourseTables;
    }


    /**
     * 添加付费课程到课程记录表中
     *
     * @param userId
     * @param coursepublish
     * @return
     */
    public XcChooseCourse addChargeCoruse(String userId, CoursePublish coursepublish) {
        //如果存在待支付记录直接返回
        LambdaQueryWrapper<XcChooseCourse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(XcChooseCourse::getUserId, userId)
                .eq(XcChooseCourse::getCourseId, coursepublish.getId())
                .eq(XcChooseCourse::getOrderType, "700002")//收费订单
                .eq(XcChooseCourse::getStatus, "701002");//待支付

        List<XcChooseCourse> xcChooseCourses = xcChooseCourseMapper.selectList(lambdaQueryWrapper);
        if (xcChooseCourses != null && xcChooseCourses.size() > 0) {
            return xcChooseCourses.get(0);
        }

        //不存在，则添加付费课程到课程记录表中
        XcChooseCourse xcChooseCourse = new XcChooseCourse();
        xcChooseCourse.setCourseId(coursepublish.getId());
        xcChooseCourse.setCourseName(coursepublish.getName());
        xcChooseCourse.setCoursePrice(coursepublish.getPrice());
        xcChooseCourse.setUserId(userId);
        xcChooseCourse.setCompanyId(coursepublish.getCompanyId());
        xcChooseCourse.setOrderType("700002");//收费课程
        xcChooseCourse.setCreateDate(LocalDateTime.now());
        xcChooseCourse.setStatus("701002");//待支付

        xcChooseCourse.setValidDays(coursepublish.getValidDays());
        xcChooseCourse.setValidtimeStart(LocalDateTime.now());
        xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(coursepublish.getValidDays()));
        xcChooseCourseMapper.insert(xcChooseCourse);
        return xcChooseCourse;
    }


    /**
     * 添加免费课程到课程记录表中
     * 添加免费课程,免费课程加入选课记录表、我的课程表
     *
     * @param userId
     * @param coursepublish
     * @return
     */
    public XcChooseCourse addFreeCourse(String userId, CoursePublish coursepublish) {
        //查询课程表中是否存在该用户的免费课程
        LambdaQueryWrapper<XcChooseCourse> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(XcChooseCourse::getCourseId, coursepublish.getId())
                .eq(XcChooseCourse::getUserId, userId)
                .eq(XcChooseCourse::getStatus, "701001")//选课类型--选课成功
                .eq(XcChooseCourse::getOrderType, "700001");//免费课程

        List<XcChooseCourse> xcChooseCourses = xcChooseCourseMapper.selectList(lambdaQueryWrapper);
        if (xcChooseCourses != null && xcChooseCourses.size() > 0) {
            return xcChooseCourses.get(0);
        }
        //没有就添加选课记录信息
        XcChooseCourse xcChooseCourse = new XcChooseCourse();
        xcChooseCourse.setCourseId(coursepublish.getId());
        xcChooseCourse.setCompanyId(coursepublish.getCompanyId());
        xcChooseCourse.setCreateDate(LocalDateTime.now());
        xcChooseCourse.setCourseName(coursepublish.getName());
        xcChooseCourse.setUserId(userId);
        xcChooseCourse.setCoursePrice(0f);//免费价格
        xcChooseCourse.setStatus("701001");//选课成功
        xcChooseCourse.setValidDays(365);
        xcChooseCourse.setOrderType("700001");
        xcChooseCourse.setValidtimeStart(LocalDateTime.now());
        xcChooseCourse.setValidtimeEnd(LocalDateTime.now().plusDays(365));
        int insert = xcChooseCourseMapper.insert(xcChooseCourse);
        if (insert <= 0) {
            XueChengPlusException.cast("没有成功的添加到课程记录表中");
        }
        return xcChooseCourse;
    }


    /**
     * 判断学习资格
     * XcCourseTablesDto
     * 学习资格状态 [{"code":"702001","desc":"正常学习"},
     * {"code":"702002","desc":"没有选课或选课后没有支付"},
     * {"code":"702003","desc":"已过期需要申请续期或重新支付"}]
     *
     * @param userId
     * @param courseId
     * @return
     */
    @Override
    public XcCourseTablesDto getLearningStatus(String userId, Long courseId) {
        //查询我的课程表
        XcCourseTables xcCourseTables = getXcCourseTables(userId, courseId);
        if (xcCourseTables == null) {//课程表为空
            //没有添加选课或者没有支付
            XcCourseTablesDto xcCourseTablesDto = new XcCourseTablesDto();
            xcCourseTablesDto.setLearnStatus("702002");
            return xcCourseTablesDto;
        }
        //正常学习
        XcCourseTablesDto xcCourseTablesDto = new XcCourseTablesDto();
        BeanUtils.copyProperties(xcCourseTables, xcCourseTablesDto);
        //判断是否过期
        boolean isExpries = xcCourseTables.getValidtimeEnd().isBefore(LocalDateTime.now());
        if (isExpries) {
            //已过期
            xcCourseTablesDto.setLearnStatus("702003");
            return xcCourseTablesDto;
        } else {
            //未过期--正常学习
            xcCourseTablesDto.setLearnStatus("702001");
            return xcCourseTablesDto;
        }

    }

    /**
     * 添加课程
     * @param chooseCourseId
     * @return
     */
    @Override
    @Transactional
    public boolean saveChooseCourseSuccess(String chooseCourseId) {
        //根据choosecourseId查询选课记录
        XcChooseCourse xcChooseCourse = xcChooseCourseMapper.selectById(chooseCourseId);
        if(xcChooseCourse == null){
            log.debug("收到支付结果通知没有查询到关联的选课记录,choosecourseId:{}",chooseCourseId);
            return false;
        }
        String status = xcChooseCourse.getStatus();
        if("701001".equals(status)){
            //添加到课程表
            addCourseTabls(xcChooseCourse);
            return true;
        }
        //待支付状态才处理
        if ("701002".equals(status)) {
            //更新为选课成功
            xcChooseCourse.setStatus("701001");
            int update = xcChooseCourseMapper.updateById(xcChooseCourse);
            if(update>0){
                log.debug("收到支付结果通知处理成功,选课记录:{}",xcChooseCourse);
                //添加到课程表
                addCourseTabls(xcChooseCourse);
                return true;
            }else{
                log.debug("收到支付结果通知处理失败,选课记录:{}",xcChooseCourse);
                return false;
            }
        }

        return false;
    }


    /**
     * 我的课程表
     * @param params
     * @return
     */
    @Override
    public PageResult<XcCourseTables> mycoursetables(MyCourseTableParams params) {
        //页码
        long pageNo = params.getPage();
        //每页记录数
        long pageSize = params.getSize();
        //分页条件
        Page<XcCourseTables> page = new Page<>(pageNo,pageSize);
        //根据用户id查询自己的课程
        String userId = params.getUserId();
        LambdaQueryWrapper<XcCourseTables> lambdaQueryWrapper = new LambdaQueryWrapper<XcCourseTables>().eq(XcCourseTables::getUserId, userId);

        //分页查询
        Page<XcCourseTables> pageResult = xcCourseTablesMapper.selectPage(page, lambdaQueryWrapper);
        List<XcCourseTables> records = pageResult.getRecords();

        //记录总数
        long total = pageResult.getTotal();
        PageResult<XcCourseTables> result = new PageResult<>(records, total, pageNo, pageSize);

        return result;
    }
}